package routes

import (
	"fmt"
	"github.com/gin-contrib/pprof"
	"github.com/gin-gonic/gin"
	"goshell.straysh.com/internal/helperF"
	"time"
)

// Router 套壳路由
type Router struct {
	*gin.Engine
}

// NewRouter 实例化路由
func NewRouter(group string, register func(*gin.RouterGroup)) *Router {
	engine := gin.New()
	r := &Router{engine}

	r.RegisterGlobalMiddlewares()
	register(r.Group(group))
	r.NoRoute(func(c *gin.Context) {
		c.JSON(404, gin.H{
			"status": 40004,
			"info":   "404 Not Found!",
			"data":   nil,
		})
	})
	r.GET("ping", func(c *gin.Context) {
		c.JSON(200, fmt.Sprintf("pong %s", helperF.TimeToTimeStr(time.Now())))
	})
	pprof.Register(engine)
	return r
}

// RegisterGlobalMiddlewares 注册全局路由中间件
func (r *Router) RegisterGlobalMiddlewares() {
	// 日志 Add a ginzap middleware, which:
	//   - Logs all requests, like a combined access and error log.
	//   - Logs to stdout.
	//   - RFC3339 with UTC time format.
	//r.Use(ginzap.Ginzap(ioc.Logger(), time.RFC3339, true))
	//r.Use(ginzap.Ginzap(ioc.ZapLogger(), "2006-01-02 15:04:05.123", true))
	if gin.Mode() != gin.ReleaseMode {
		r.Use(gin.Logger())
	}

	// Logs all panic to error log
	//   - stack means whether output the stack info.
	//r.Use(ginzap.RecoveryWithZap(bootstrap.Logger, true))
	r.Use(gin.Recovery())

	//r.Use(sessions.Sessions("dstore-dev-session", redis.NewSession(ioc.Config().Data.Session)))

	//r.Use(cors.New(cors.Config{
	//	AllowOrigins:     []string{"http://localhost"},
	//	AllowMethods:     []string{"GET", "POST", "PUT"},
	//	AllowHeaders:     []string{"*"},
	//	ExposeHeaders:    []string{"*"},
	//	AllowCredentials: true,
	//	AllowOriginFunc: func(origin string) bool {
	//		ps, _ := url.ParseRequestURI(origin)
	//		host := strings.Split(ps.Host, ":")[0]
	//		siteDomain := ioc.Config().Oss.OuterNet
	//		siteParts, _ := url.ParseRequestURI(siteDomain)
	//		siteHost := strings.Replace(strings.Split(siteParts.Host, ":")[0], "-storage", "-developer", 1)
	//		return host == "127.0.0.1" || host == "localhost" || host == siteHost
	//	},
	//}))
}
